package com.dawnling.datepickerdemo;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;


import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.BitmapDrawable;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.PopupWindow;

/**
 * PopWindow for Date Pick
 */
public class DatePickerPopWin_Double extends PopupWindow implements OnClickListener {

    private static final int DEFAULT_MIN_YEAR = 1900;
    public ImageView cancelBtn;
    public Button confirmBtn;
    public View pickerContainerV;
    public View contentView;//root view
    
    public LoopView yearLoopView;
    public LoopView monthLoopView;
    public LoopView dayLoopView;
    private LoopView yearLoopView1;
    private LoopView monthLoopView1;
    private LoopView dayLoopView1;

    private int minYear; // min year
    private int maxYear; // max year
    private int yearPos = 0;
    private int monthPos = 0;
    private int dayPos = 0;
    private int yearPos1 = 0;
    private int monthPos1 = 0;
    private int dayPos1 = 0;
    private Context mContext;
    private OnDatePickedListener mListener;//监听事件

    List<String> yearList = new ArrayList();
    List<String> monthList = new ArrayList();
    List<String> dayList = new ArrayList();

    public static class Builder {
        //Required
        private Context context;
        private OnDatePickedListener listener;

        public Builder(Context context, OnDatePickedListener listener) {
            this.context = context;
            this.listener = listener;
        }

        //Option
        private int minYear = DEFAULT_MIN_YEAR;
        private int maxYear = Calendar.getInstance().get(Calendar.YEAR) + 1;
        private String dateChose = getStrDate();

        public Builder minYear(int minYear) {
            this.minYear = minYear;
            return this;
        }

        public Builder maxYear(int maxYear) {
            this.maxYear = maxYear;
            return this;
        }

        public Builder dateChose(String dateChose) {
            this.dateChose = dateChose;
            return this;
        }

        public DatePickerPopWin_Double build() {
            if (minYear > maxYear) {
                throw new IllegalArgumentException();
            }
            return new DatePickerPopWin_Double(this);
        }
    }

    public DatePickerPopWin_Double(Builder builder) {
        this.minYear = builder.minYear;
        this.maxYear = builder.maxYear;
        this.mContext = builder.context;
        this.mListener = builder.listener;
        setSelectedDate(builder.dateChose);
        initView();
    }

    private void initView() {
        contentView = LayoutInflater.from(mContext).inflate(R.layout.layout_date_picker_huiyi, null);
        cancelBtn = (ImageView) contentView.findViewById(R.id.btn_cancel);//取消按钮
        confirmBtn = (Button) contentView.findViewById(R.id.btn_confirm);//确定按钮
        pickerContainerV = contentView.findViewById(R.id.container_picker);
        
        yearLoopView = (LoopView) contentView.findViewById(R.id.picker_year);
        monthLoopView = (LoopView) contentView.findViewById(R.id.picker_month);
        dayLoopView = (LoopView) contentView.findViewById(R.id.picker_day);
        
        yearLoopView1 = (LoopView) contentView.findViewById(R.id.picker_year1);
        monthLoopView1 = (LoopView) contentView.findViewById(R.id.picker_month1);
        dayLoopView1 = (LoopView) contentView.findViewById(R.id.picker_day1);

        //set checked listen
        yearLoopView.setLoopListener(new LoopScrollListener() {
            @Override
            public void onItemSelect(int item) {
                yearPos = item;
                initDayPickerView();
            }
        });
        monthLoopView.setLoopListener(new LoopScrollListener() {
            @Override
            public void onItemSelect(int item) {
                monthPos = item;
                initDayPickerView();
            }
        });
        dayLoopView.setLoopListener(new LoopScrollListener() {
            @Override
            public void onItemSelect(int item) {
                dayPos = item + 1;
            }
        });
        
        yearLoopView1.setLoopListener(new LoopScrollListener() {
        	@Override
        	public void onItemSelect(int item) {
        		yearPos1 = item;
        		initDayPickerView1();
        	}
        });
        monthLoopView1.setLoopListener(new LoopScrollListener() {
        	@Override
        	public void onItemSelect(int item) {
        		monthPos1 = item;
        		initDayPickerView1();
        	}
        });
        dayLoopView1.setLoopListener(new LoopScrollListener() {
        	@Override
        	public void onItemSelect(int item) {
        		dayPos1 = item + 1;
        	}
        });

        initPickerViews(); // init year and month loop view
        initDayPickerView(); //init day loop view
        
        initPickerViews1(); // init year and month loop view
        initDayPickerView1(); //init day loop view

        cancelBtn.setOnClickListener(this);
        confirmBtn.setOnClickListener(this);
        contentView.setOnClickListener(this);

        setTouchable(true);
        setFocusable(true);
        setBackgroundDrawable(new BitmapDrawable());
        setAnimationStyle(R.style.FadeInPopWin);
        setContentView(contentView);
        setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        setHeight(ViewGroup.LayoutParams.MATCH_PARENT);
    }

    /**
     * Init year and month loop view,
     * Let the day loop view be handled separately
     */
    private void initPickerViews() {

        int yearCount = maxYear - minYear;

        for (int i = 0; i < yearCount; i++) {
            yearList.add(format2LenStr(minYear + i));
        }
        for (int j = 0; j < 12; j++) {
            monthList.add(format2LenStr(j+1));
        }

        yearLoopView.setDataList((ArrayList) yearList);
        yearLoopView.setInitPosition(yearPos);

        monthLoopView.setDataList((ArrayList) monthList);
        monthLoopView.setInitPosition(monthPos);
    }
    
    private void initPickerViews1() {
    	
    	int yearCount = maxYear - minYear;
    	
    	for (int i = 0; i < yearCount; i++) {
    		yearList.add(format2LenStr(minYear + i));
    	}
    	for (int j = 0; j < 12; j++) {
    		monthList.add(format2LenStr(j+1));
    	}
    	
    	yearLoopView1.setDataList((ArrayList) yearList);
    	yearLoopView1.setInitPosition(yearPos1);
    	
    	monthLoopView1.setDataList((ArrayList) monthList);
    	monthLoopView1.setInitPosition(monthPos1);
    }

    /**
     * Init day item
     */
    private void initDayPickerView() {

        int dayMaxInMonth;
        Calendar calendar = Calendar.getInstance();
        dayList = new ArrayList<String>();

        calendar.set(Calendar.YEAR, minYear + yearPos);
        calendar.set(Calendar.MONTH, monthPos);

        //get max day in month
        dayMaxInMonth = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
        for (int i = 1; i < dayMaxInMonth + 1; i++) {
            dayList.add(format2LenStr(i));
        }

        dayLoopView.setDataList((ArrayList) dayList);
        dayLoopView.setInitPosition(dayPos - 1 );
    }
    
    private void initDayPickerView1() {
    	
    	int dayMaxInMonth;
    	Calendar calendar = Calendar.getInstance();
    	dayList = new ArrayList<String>();
    	
    	calendar.set(Calendar.YEAR, minYear + yearPos1);
    	calendar.set(Calendar.MONTH, monthPos1);
    	
    	//get max day in month
    	dayMaxInMonth = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
    	for (int i = 1; i < dayMaxInMonth + 1; i++) {
    		dayList.add(format2LenStr(i));
    	}
    	
    	dayLoopView1.setDataList((ArrayList) dayList);
    	dayLoopView1.setInitPosition(dayPos1 - 1 );
    }

    /**
     * set selected date position value when initView.
     *
     * @param dateStr
     */
    public void setSelectedDate(String dateStr) {

        if (!TextUtils.isEmpty(dateStr)) {

            long milliseconds = getLongFromyyyyMMdd(dateStr);
            Calendar calendar = Calendar.getInstance(Locale.CHINA);

            if (milliseconds != -1) {

                calendar.setTimeInMillis(milliseconds);
                yearPos = calendar.get(Calendar.YEAR) - minYear;
                monthPos = calendar.get(Calendar.MONTH);
                dayPos = calendar.get(Calendar.DAY_OF_MONTH);
                
                yearPos1 = calendar.get(Calendar.YEAR) - minYear;
                monthPos1 = calendar.get(Calendar.MONTH);
                dayPos1 = calendar.get(Calendar.DAY_OF_MONTH);
            }
        }
    }

    /**
     * Show date picker popWindow
     *
     * @param activity
     */
    public void showPopWin(Activity activity) {

        if (null != activity) {

            TranslateAnimation trans = new TranslateAnimation(
                    Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF,
                    0, Animation.RELATIVE_TO_SELF, 1,
                    Animation.RELATIVE_TO_SELF, 0);

            showAtLocation(activity.getWindow().getDecorView(), Gravity.BOTTOM,
                    0, 0);
            trans.setDuration(400);
            trans.setInterpolator(new AccelerateDecelerateInterpolator());

            pickerContainerV.startAnimation(trans);
        }
    }

    /**
     * Dismiss date picker popWindow
     */
    public void dismissPopWin() {

        TranslateAnimation trans = new TranslateAnimation(
                Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0,
                Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 1);

        trans.setDuration(400);
        trans.setInterpolator(new AccelerateInterpolator());
        trans.setAnimationListener(new AnimationListener() {

            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationRepeat(Animation animation) {
            }

            @Override
            public void onAnimationEnd(Animation animation) {

                dismiss();
            }
        });

        pickerContainerV.startAnimation(trans);
    }

    @Override
    public void onClick(View v) {
    	
        if (v == contentView || v.getId() == R.id.btn_cancel) {
            dismissPopWin();
        } else if (v == confirmBtn) {
        	
            if (null != mListener) {

                int year = minYear + yearPos;
                int month = monthPos;
                int day = dayPos ;
                StringBuffer sb = new StringBuffer();
                
                int year1 = minYear + yearPos1;
                int month1 = monthPos1;
                int day1 = dayPos1 ;
                StringBuffer sb1 = new StringBuffer();

                if (yearPos != 0) {
                    sb.append(String.valueOf(year));
//                    sb.append("-");
                    if (monthPos != 0) {
                        sb.append(format2LenStr(month + 1));
//                        sb.append("-");
                        if (dayPos != 0) {
                            sb.append(format2LenStr(day));
                        }
                    }
                }
                if (yearPos1 != 0) {
                	sb1.append(String.valueOf(year1));
//                	sb1.append("-");
                	if (monthPos1 != 0) {
                		sb1.append(format2LenStr(month1 + 1));
//                		sb1.append("-");
                		if (dayPos1 != 0) {
                			sb1.append(format2LenStr(day1));
                		}
                	}
                }
                mListener.onDatePickCompleted(year, month, day, sb.toString());
                mListener.onDatePickCompleted1(year1, month1, day1, sb1.toString());
            }
            dismissPopWin();
        }
    }

    /**
     * get long from yyyy-MM-dd
     *
     * @param date
     * @return
     */
    public static long getLongFromyyyyMMdd(String date) {
        SimpleDateFormat mFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
        Date parse = null;
        try {
            parse = mFormat.parse(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        if (parse != null) {
            return parse.getTime();
        } else {
            return -1;
        }
    }

    public static String getStrDate() {
        SimpleDateFormat dd = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA);
        return dd.format(new Date());
    }

    /**
     * Transform int to String with prefix "0" if less than 10
     *
     * @param num
     * @return
     */
    public static String format2LenStr(int num) {
        return (num < 10) ? "0" + num : String.valueOf(num);
    }

    public static int spToPx(Context context, int spValue) {
        final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
        return (int) (spValue * fontScale + 0.5f);
    }

    public interface OnDatePickedListener {

        /**
         * Listener when date has been checked
         *
         * @param year
         * @param month
         * @param day
         * @param dateDesc yyyy-MM-dd
         */
        void onDatePickCompleted(int year, int month, int day, String dateDesc);
        void onDatePickCompleted1(int year, int month, int day, String dateDesc);
    }
}
